package com.haisen.core.shiro.credentials;

import com.haisen.dataobject.enums.LoginType;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>User: Zhang Kaitao
 * <p>Date: 14-1-28
 * <p>Version: 1.0
 */
@Slf4j
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {

    /**
     *多线程下的自增安全
     * key name,count
     */
    private Cache<String, AtomicInteger> passwordRetryCache;

    public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
    }

    /**
     *证书匹配,token和info是否匹配
     * @param token
     * @param info
     * @return
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        //判断用登录类型，用户名+密码，第三方登录
         /* UsernamePasswordAndClientToken tk = (UsernamePasswordAndClientToken) token;
        UsernamePasswordAndClientToken.TokenType  tokenType = ((UsernamePasswordAndClientToken) token).getTokenType();
        if(tokenType.equals(UsernamePasswordAndClientToken.TokenType.CLIENT)){
            return true;
        }*/
         CustomToken tk = (CustomToken) token;
         LoginType loginType = tk.getType();
         if (loginType.equals(LoginType.NOPASSWD)){
             log.info("免密码登录，通过");
             return true;
         }

        //主体,系统中主体就是用户
        String username = (String)token.getPrincipal();
        //retry count + 1
        AtomicInteger retryCount = passwordRetryCache.get(username);
        log.info("2、登录证书验证：用户名{},登录次数={}",username,retryCount );
        if(retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }
        if(retryCount.incrementAndGet() > 5) {
            //if retry count > 5 throw
            throw new ExcessiveAttemptsException();
        }

        boolean matches = super.doCredentialsMatch(token, info);
        //token: username,password ,rememberme,host:
        //info:principals:admin credentials:d3c59d25033dbf980d29554025c23a75，credentialsSalt:YWRtaW44ZDc4ODY5ZjQ3MDk1MTMzMjk1OTU4MDQyNGQ0YmY0Zg==
        log.info("3、匹配结果={}",matches);
        if(matches) {
            //clear retry count
            passwordRetryCache.remove(username);
        }
        return matches;
    }
}
